<template>
  <div class="wrap">
    <div class="main">
      <el-form label-width="80px">
        <el-form-item label="标题">
          <el-input style="width: 60%" v-model="article.articleTitle"></el-input>
        </el-form-item>
        <el-form-item>
          <el-card>
            <quill-editor

              ref="myLQuillEditor"
              v-model="article.articleContent"
              :options="editorOption"
              class="editor"
              @blur="onEditorBlur"
              @focus="onEditorFocus"
              @change="onEditorChange">
            </quill-editor>
          </el-card>
        </el-form-item>

        <el-form-item label="标签">
          <el-checkbox-group v-model="article.articleTags">
            <el-checkbox v-for="(item,index) in tags" :key="index" :label="item.tagsName"></el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="分类">
          <el-select v-model="article.articleClassify" placeholder="请选择">
            <el-option
              v-for="(item,index) in classify"
              :key="index"
              :label="item.className"
              :value="item.className">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit()" :disabled="submitButtonDisable" plain>提 交</el-button>
          <el-button type="info" icon="el-icon-message" @click="handleSubmitDraft()" circle>保存到草稿箱</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
// 引入样式和quillEditor
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import {quillEditor} from 'vue-quill-editor'
import {addBlog, addBlogDraft, getClassList, getTagsList} from "../../request/request";
import debounce from "lodash.debounce";
import {checkUpdate, getBlogDrafts} from "../../request/reqManage";

// 工具栏配置项
const toolbarOptions = [
  // 加粗 斜体 下划线 删除线 -----['bold', 'italic', 'underline', 'strike']
  ['bold', 'italic', 'underline', 'strike'],
  // 引用  代码块-----['blockquote', 'code-block']
  ['blockquote', 'code-block'],
  // 1、2 级标题-----[{ header: 1 }, { header: 2 }]
  [{header: 1}, {header: 2}],
  // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
  [{list: 'ordered'}, {list: 'bullet'}],
  // 上标/下标-----[{ script: 'sub' }, { script: 'super' }]
  [{script: 'sub'}, {script: 'super'}],
  // 缩进-----[{ indent: '-1' }, { indent: '+1' }]
  [{indent: '-1'}, {indent: '+1'}],
  // 文本方向-----[{'direction': 'rtl'}]
  [{direction: 'rtl'}],
  // 字体大小-----[{ size: ['small', false, 'large', 'huge'] }]
  [{size: ['small', false, 'large', 'huge']}],
  // 标题-----[{ header: [1, 2, 3, 4, 5, 6, false] }]
  [{header: [1, 2, 3, 4, 5, 6, false]}],
  // 字体颜色、字体背景颜色-----[{ color: [] }, { background: [] }]
  [{color: []}, {background: []}],
  // 字体种类-----[{ font: [] }]
  [{font: []}],
  // 对齐方式-----[{ align: [] }]
  [{align: []}],
  // 清除文本格式-----['clean']
  ['clean'],
  // 链接、图片、视频-----['link', 'image', 'video']
  ['image', 'video']
]
let timer;


export default {
  name: "ManageBlogs",
  components: {
    quillEditor
  },

  data() {
    return {
      content: '',
      //禁用按钮
      submitButtonDisable: false,

      article: {
        "articleId": '',
        "articleTitle": '',
        "articleContent": '',
        "articleClassify": '',
        "articleTags": [],
        "articleUnlike": '',
        "articleUsername": this.$user,
        "articleRanking": 1,
        "articleCover": '',
        "articleCollect": '',
        "articleLike": '',
        "articleTime": '',
        "articleUpdateTime": "",
        "articleStatus": 3
      },
      tags: [],
      classify: [],
      editorOption: {
        modules: {
          toolbar: toolbarOptions
        },
        theme: 'snow',
        placeholder: '请输入正文'

      },
      params: {}
    }
  },
  methods: {
    // 失去焦点事件
    onEditorBlur(e) {
    },
    // 获得焦点事件
    onEditorFocus(e) {
    },

    // 内容改变事件
    onEditorChange(e) {
      //每次编辑都赋值,不为null了,就不会自动保存
      this.debounce()
    },
    /**
     * 保存文章
     */
    handleSubmit() {
      //禁用点击按钮
      this.submitButtonDisable = true
      this.article.articleTags = JSON.stringify(this.article.articleTags)
      this.article.articleStatus = 200
      this.$mr.checkUpdate(this.article).then((data) => {
        if (data.code !== 200) {
          this.$message.error(data.data)
          this.submitButtonDisable = false
          return
        }
        this.$message.success('提交成功')
        this.submitButtonDisable = false
        this.article = "";
        this.$router.push({
          path: '/manageBlogList',
        })
      })
    },

    /**
     * todo
     * 点击保存到草稿箱
     * 浏览器或者页面关闭自动保存到草稿
     * 指定时间没有操作,则自动保存到草稿箱
     * 编辑器市区焦点保存到草稿箱(未完成)
     */
    handleSubmitDraft() {
      // this.article.articleId =
      this.submitButtonDisable = true
      this.article.articleTags = JSON.stringify(this.article.articleTags)
      this.article.articleStatus = 300
      // this.article.articleId=null
      this.$request.addBlog(this.article).then((data) => {
        if (data.code !== 200) {
          this.$notify.error(data.data)
          return
        }
        this.$notify.success('已保存到草稿箱')
        this.submitButtonDisable = false
        this.article = "";
        this.$router.push({
          path: '/manageBlogList',
        })
      })
    },

    /**
     * 防抖 , 十分钟保存一次
     */
    debounce() {
      if (timer) {
        clearTimeout(timer);
      }
      timer = setTimeout(() => {
        this.$message.warning('长时间未操作,已自动帮您保存到草稿')
        this.handleSubmitDraft()
        timer = undefined;
      }, 1000 * 60 * 10);
    },
    /**
     * 获取所有标签
     */
    getTagsList() {
      this.$request.getTagsList().then((data) => {
        this.tags = data.data
      })
    },
    getClassList() {
      this.$request.getClassList().then((data) => {
        this.classify = data.data
      })
    },


    /**
     * 监听浏览器关闭或者刷新
     * 防止用户浏览器被刷新或者关闭后内容需要重新编辑,所以把内容存到storage,每次刷新从storage中读取内容
     * @param e
     */
    beforeunloadFn(e) {
      localStorage.setItem('article', JSON.stringify(this.article))
      this.handleSubmitDraft()
    },
    /**
     * 点击发布文章页面编辑传过来的数据
     */
    getBlogUpdate() {
      this.$mr.getBlogDrafts(this.$route.query.articleId).then((data) => {
        this.article = data.data
        this.article.articleTags = JSON.parse(data.data.articleTags);
      })
    }
  },

  created() {
    this.getTagsList()
    this.getClassList()
    this.getBlogUpdate()
    //先看看用户上次有没有编辑的内容,如果有的话就读取上次编辑的内容
    let item = localStorage.getItem('article');

    if (item !== null) {
      this.article = JSON.parse(item)
    }

    window.addEventListener('beforeunload', e => this.beforeunloadFn(e))
  },

  destroyed() {
    window.removeEventListener('beforeunload', e => this.beforeunloadFn(e))
  },
  mounted() {
    window.addEventListener('beforeunload', e => this.beforeunloadHandler(e))
  },
}
</script>

<style scoped>
.main {
  width: 75%;
  margin: auto;
}

.wrap {
  width: 100%;
  min-height: 700px;
  background-color: #fff;
}

.local-quill-editor {
  background-color: #fff;
}

.editor {

  height: 500px;
}
</style>
